package com.quanfaqiang.demo1.config;


import com.quanfaqiang.demo1.service.UserService;
import com.quanfaqiang.demo1.service.impl.WebSocketHandlerImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final UserService userService;  // 注入 UserService

    public WebSocketConfig(UserService userService) {
        this.userService = userService;  // 在构造方法中注入
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        WebSocketHandlerImpl handler = new WebSocketHandlerImpl(userService);  // 手动创建 WebSocketHandlerImpl 实例并注入 UserService
        registry.addHandler(handler, "/ws")
                .addInterceptors(new HttpSessionHandshakeInterceptor())
                .setAllowedOrigins("*"); // 允许所有域名访问
    }

}
